package com.vancouver.knows.ui.activity;

import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.bean.SplashAdInfo;
import com.vancouver.knows.business.task.mark.SplashAdInfoTaskMark;
import com.vancouver.knows.event.SystemEvent;
import com.vancouver.knows.event.SystemEventConst;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.homePage.HomeFragment;
import com.vancouver.knows.util.AppUtils;


/**
 * Created by Chris Li on 2016-08-10.
 */
public class TutorialActivity extends BaseActivity implements HomeFragment.OnSplashAdListeners, View.OnClickListener, SystemEvent.EventListener {

    public static final String TUTORIAL_EXTRA = "tutorial_extra";

    private String mWalkThrough = null;

    private TutorialPagerAdapter tutorialPagerAdapter;
    private RadioGroup indicators;
    private ViewPager tutorialPager;
    private boolean isRuningToZexo = false;
    private boolean isRuningToOther = false;
    private int currentPosition = 0;

    private RelativeLayout rootView;

    /**======开屏广告变量=====**/
    private View splashView = null;
    private SplashAdInfo splashAdInfo;
    private ImageView splashImage;
    private TextView JumpTxt;
    private int timeLength;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SystemEvent.removeListener(SystemEventConst.EVENT_ACTION_UPDATE_SPLASH_AD, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        rootView = new RelativeLayout(this);
        rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(rootView);
        HomeFragment.newInstance().setSplashAdLiseners(this);

        SystemEvent.addListener(SystemEventConst.EVENT_ACTION_UPDATE_SPLASH_AD, this);

        mWalkThrough = getIntent().getStringExtra(TUTORIAL_EXTRA);
        if (mWalkThrough != null) {
            switch (mWalkThrough) {
                case BSharedPrefManager.WALKTHOUGH_1:
                    setViewPagerTutorial(rootView, null, 0);

                    break;
                case BSharedPrefManager.WALKTHOUGH_2:
                   // setSingleImageTutorial(rootView);
                    break;
                case BSharedPrefManager.WALKTHOUGH_SPLASH_AD:
                    openSplashAd();
                    break;
            }
        } else {
            finish();
        }
    }

    private void setViewPagerTutorial(final RelativeLayout rootView, String type, int pos) {

        if (tutorialPager == null) {
            tutorialPager = new ViewPager(this);
            tutorialPager.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        }

        if (tutorialPagerAdapter == null) {
            tutorialPagerAdapter = new TutorialPagerAdapter();
            tutorialPager.setAdapter(tutorialPagerAdapter);
            rootView.addView(tutorialPager);
        }

        if (indicators == null) {
            indicators = new RadioGroup(this);
            RelativeLayout.LayoutParams indicatorsParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            indicatorsParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            indicatorsParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
            indicatorsParams.setMargins(0, 0, 0, getResources().getDimensionPixelSize(R.dimen.indicator_margin));
            indicators.setLayoutParams(indicatorsParams);
            indicators.setOrientation(LinearLayout.HORIZONTAL);
            rootView.addView(indicators);
        }

        int margin = getResources().getDimensionPixelSize(R.dimen.view_padding);
        int indicatorCount = tutorialPagerAdapter.getCount();
        int size = (int) getResources().getDimension(R.dimen.indicator_size);
        for (int i = 0; i < indicatorCount; i++) {
            RadioButton indicator = new RadioButton(this);
            RadioGroup.LayoutParams radioParams = new RadioGroup.LayoutParams(size, size);
            radioParams.setMargins(margin, 0 , margin, 0);
            indicator.setLayoutParams(radioParams);
            if (StringUtil.isEmptyString(type)) {
                indicator.setBackgroundResource(R.drawable.circle_indicator_selector_number_1);
            } else {
                indicator.setBackgroundResource(R.drawable.circle_indicator_selector);
            }

            indicator.setButtonDrawable(new StateListDrawable());
            indicator.setText("");
            indicators.addView(indicator);
        }

        RadioButton indicator = (RadioButton) indicators.getChildAt(pos);
        indicator.setChecked(true);
        tutorialPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                System.out.println("onPageScrolled");
            }

            @Override
            public void onPageSelected(int position) {
                System.out.println("onPageSelected");
                if (position == 0) {
                    isRuningToZexo = true;
                    isRuningToOther = false;
                } else if (position > 0) {
                    isRuningToZexo = false;
                    isRuningToOther = true;
                }

                currentPosition = position;

//              RadioButton indicator = (RadioButton) indicators.getChildAt(position);
//              indicator.setChecked(true);


            }

            @Override
            public void onPageScrollStateChanged(int state) {
                System.out.println("onPageScrollStateChanged");

                if (state == 0 ) {
                    if (isRuningToOther) {
                        indicators.removeAllViews();
                        setViewPagerTutorial(rootView, "review", currentPosition);
                        isRuningToOther = false;
                    } else if (isRuningToZexo) {
                        indicators.removeAllViews();
                        setViewPagerTutorial(rootView, null, 0);
                        isRuningToZexo = false;
                    }
                }
            }
        });

    }

//    private void setSingleImageTutorial(RelativeLayout rootView) {
//        ImageView tutorialImage = new ImageView(this);
//        tutorialImage.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
//        rootView.addView(tutorialImage);
//        Picasso.with(this).load(R.drawable.walkthrough2).fit().into(tutorialImage);
//        tutorialImage.setOnClickListener(this);
//    }

    private void setSplashViews() {
        if (splashView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(imContext);
            splashView = layoutInflater.inflate(R.layout.splash_ad_view, rootView, false);
            rootView.addView(splashView);

            splashImage = (ImageView)splashView.findViewById(R.id.splash_img);
            JumpTxt = (TextView)splashView.findViewById(R.id.jump_text);
        }
    }

    private void setListeners() {
        /**=========事件定义===============**/
        splashImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (splashAdInfo == null) return;
                Intent webIntent =  new Intent(Intent.ACTION_VIEW);
                webIntent.setData(Uri.parse(splashAdInfo.getRedirUrl()));
                imContext.startActivity(webIntent);
            }
        });

        JumpTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
    }

    private boolean isHaveSplashAd = false;
    private void setSplashAd() {
        /**===========数据处理===================**/
        if (splashAdInfo != null) {
            if (Integer.valueOf(splashAdInfo.getErrorCode()) != 0 || StringUtil.isEmptyString(splashAdInfo.getImageUrl())) {
                //显示默认图片， 点击跳过按钮不显示
                JumpTxt.setVisibility(View.GONE);
                isHaveSplashAd = false;

            } else {
                //显示开屏广告
                JumpTxt.setVisibility(View.VISIBLE);
                isHaveSplashAd = true;
                JumpTxt.setText(imContext.getString(R.string.click_jump_tip));
                Glide.with(this).load(splashAdInfo.getImageUrl()).placeholder(R.drawable.splash).crossFade().into(splashImage);

            }

            timeLength = Integer.valueOf(splashAdInfo.getTimeLength());
            handler.post(runnable);
        }

    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isHaveSplashAd) {
                JumpTxt.setText(Html.fromHtml(imContext.getString(R.string.click_jump, timeLength)));
            }

            if (timeLength <= 0) {
                finishActivity();
            } else {
                handler.postDelayed(this, 1000);
            }
            timeLength--;
        }
    };

    private void setSplashAdInfo() {
        splashAdInfo = imContext.getBusinessModule().getCacheManager().getSplashAdInfoCache();
    }

    /**
     * 显示开屏广告
     */
    private void openSplashAd() {
        setSplashViews();
        setSplashAdInfo();
        setListeners();
        setSplashAd();
    }

    private void finishActivity() {
        if (imContext != null) {
            imContext.getSharedPrefManager().setHasSeenWalkThrough(mWalkThrough);
        }
        HomeFragment.newInstance().clearOnSplashAdLiseners();
        finish();
    }

    @Override
    public void onClick(View v) {
        //onBackPressed();
        finishActivity();
    }

//    @Override
//    public void onBackPressed() {
//        imContext.getSharedPrefManager().setHasSeenWalkThrough(mWalkThrough);
//        HomeFragment.newInstance().clearOnSplashAdLiseners();
//        super.onBackPressed();
//    }

    @Override
    public void showSplashAd() {
        setSplashAdInfo();
        setSplashAd();
    }

    @Override
    public void onEvent(SystemEventConst eventType, Intent data) {
        if (eventType == SystemEventConst.EVENT_ACTION_UPDATE_SPLASH_AD) {
            showSplashAd();
        }

    }

    public class TutorialPagerAdapter extends PagerAdapter {

        private int[] mResourceIds;

        public TutorialPagerAdapter() {
            this.mResourceIds = new int[]{
                    R.drawable.walkthrough_android_00,
                    R.drawable.walkthrough_android_01,
                    R.drawable.walkthrough_android_02,
                    R.drawable.walkthrough_android_03};
        }

        @Override
        public int getCount() {
            return mResourceIds.length;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            ImageView image = new ImageView(container.getContext());
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            Picasso.with(container.getContext())
                    .load(mResourceIds[position])
                    .fit()
                    .into(image);

            container.addView(image);
            if (position == mResourceIds.length - 1) {
                image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //onBackPressed();
                        finishActivity();
                    }
                });
            }
            return image;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((ImageView) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

}
